package user_private_key

import (
	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/repository/mongodb/user"
	"net/http"
)

type listRequest struct {
	UserId    string `form:"userId"`
	PageIndex uint   `form:"pageIndex"` // 第几页
	PageSize  uint   `form:"pageSize"`  // 每页显示条数
}

type Page struct {
	Total int64       `json:"total"`
	List  interface{} `json:"list"`
}

func (h *handler) List() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listRequest)
		res := new(createResponse)

		userInfo := ctx.GetInfo("userInfo").(*user.User)
		req.UserId = userInfo.Id
		if err := ctx.ShouldBindQuery(&req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithError(err),
			)
			return
		}

		productList, err := h.keyService.List(ctx, req.UserId, req.PageIndex, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.GetUserPrivateKeyListError,
				code.Text(code.GetUserPrivateKeyListError)).WithError(err),
			)
			return
		}

		count, err := h.keyService.Count(ctx, req.UserId)

		page := new(Page)
		page.Total = count
		page.List = productList

		res.Code = code.StatusOK
		res.Data = page
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
